<?php

namespace app\common\model;

class DutyArrange extends \think\Model
{
    use \app\common\model\TimeCommon;

    public function assistant()
    {
        return $this->belongsTo('Assistant');
    }

    /**
     * 检查某人是否值班
     * @param int $assistantID 要检查的助理的ID
     * @param table $param getTimeDetail()返回的数据
     * @return bool
     */
    public static function checkDuty($assistantID, $buildingName, $termID, $week, $classWeek)
    {
        $arrange = DutyArrange::where([
            'term_id' => $termID,
            'week' => $week,
            'building' => $buildingName,
            'assistant_id' => $assistantID
        ])->whereRaw(
            '(duty_classweek&:class_week)<>0',
            ['class_week' => $classWeek]
        )->find();
        return !!$arrange;
    }

    /**
     * 筛选出指定时间值班的助理的信息
     *
     * @param string $date  指定的日期
     * @param string|null $building 指定教学楼
     * @return void
     */
    public function getDutyAssistantDetial(string $date, $building)
    {
        $param = $this->getTimeDetail($date);
        if (!$param['status']) {
            $this->error = $param['errmsg'];
            return false;
        }
        $arrangeQ = DutyArrange::where([
            'term_id' => $param['term']->id,
            'week' => $param['week']
        ]);
        if ($building) {
            $arrangeQ = $arrangeQ->where('building', $building);
        }

        $arrange = $arrangeQ->whereRaw('(duty_classweek&:class_week)<>0', ['class_week' => $param['class_week']])
            ->visible(['duty_classtime', 'assistant_id','building'])->select()->toArray();

        $table = [];
        foreach ($arrange as $v) {
            if (!isset($table[$v['assistant_id']])) {
                $table[$v['assistant_id']] = model("Assistant")->where('id', $v['assistant_id'])->visible(['name', 'class_name', 'phone'])->find()->toArray();
                $table[$v['assistant_id']]['duty_classtime'] = 0;
                $table[$v['assistant_id']]['building']=$v['building'];
            }
            //因为考虑到值班表和助理表可能不同步可能导致找不到助理信息,故需要判断
            if ($table[$v['assistant_id']])
                $table[$v['assistant_id']]['duty_classtime'] |= $v['duty_classtime'];
        }
        usort($table, function ($a, $b) {
            return $a['duty_classtime'] - $b['duty_classtime'];
        });

        $ret = array();
        foreach ($table as $k => $v) {
            $table[$k]['duty_classtime'] = bitmapToStr($table[$k]['duty_classtime']);
            array_push($ret, $table[$k]);
        }
        return $ret;
    }
}
